<template>
  <view class="content">
    <!-- 顶部导航 -->
    <page-header title="回收站" :showBack="true"> </page-header>

    <!-- 主体内容 -->
    <view class="page-body">
      <!-- 待办列表 -->
      <scroll-view
        class="todo-container"
        scroll-y="true"
        @scrolltolower="loadMore"
      >
        <trash-todo-list
          :todos="deletedTodoList"
          @delete="permanentDelete"
          @restore="restoreTodo"
        />
      </scroll-view>
    </view>
  </view>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from "vue";
import pageHeader from "@/components/pageHeader.vue";
import TrashTodoList from "@/components/TrashTodoList.vue";
import { todoApi } from "@/api";

// 回收站数据
const deletedTodos = ref([]);

// 已删除待办列表
const deletedTodoList = computed(() => {
  return deletedTodos.value.map((item) => ({
    id: item.todoItemId,
    content: item.content,
    completed: item.completed,
    deleted: true,
    createdAt: item.createdAt,
    updatedAt: item.updatedAt,
    labels: item.labelId || [],
  }));
});

// 获取已删除待办列表数据的方法
const loadDeletedTodoList = async () => {
  try {
    const res = await todoApi.getDeletedTodoList();
    if (res.success && res.data) {
      // 存储已删除待办数据
      deletedTodos.value = res.data;
    }
  } catch (error) {
    console.error("获取已删除待办列表失败:", error);
  }
};

// 永久删除待办
const permanentDelete = (id) => {
  uni.showModal({
    title: "永久删除",
    content: "确定要永久删除这个待办事项吗？此操作无法撤销。",
    success: async function (res) {
      if (res.confirm) {
        try {
          // 调用彻底删除API
          const response = await todoApi.deleteTodoPermanently([id]);

          if (response.success) {
            // 从回收站列表中删除
            deletedTodos.value = deletedTodos.value.filter(
              (item) => item.todoItemId !== id
            );

            // 发送全局事件，同步删除首页中的数据
            uni.$emit("permanentDeleteTodo", id);

            uni.showToast({
              title: "永久删除成功",
              icon: "success",
            });
          } else {
            uni.showToast({
              title: response.msg || "删除失败",
              icon: "none",
            });
          }
        } catch (error) {
          console.error("永久删除失败:", error);
          uni.showToast({
            title: "删除失败，请重试",
            icon: "none",
          });
        }
      }
    },
  });
};

// 恢复待办
const restoreTodo = async (id) => {
  try {
    // 调用恢复API
    const response = await todoApi.restoreTodo({ id: id });

    if (response.success) {
      // 查找待办
      const todoIndex = deletedTodos.value.findIndex(
        (item) => item.todoItemId === id
      );
      if (todoIndex !== -1) {
        // 从回收站列表中移除
        deletedTodos.value.splice(todoIndex, 1);
      }

      // 发送全局事件，通知首页刷新数据
      uni.$emit("refreshTodoList");
      uni.$emit("todoRestored", response.data);

      uni.showToast({
        title: "待办已恢复",
        icon: "success",
      });
    } else {
      uni.showToast({
        title: response.msg || "恢复失败",
        icon: "none",
      });
    }
  } catch (error) {
    console.error("恢复待办失败:", error);
    uni.showToast({
      title: "恢复失败，请重试",
      icon: "none",
    });
  }
};

const loadMore = () => {
  console.log("加载更多回收站待办...");
};

// 页面加载
onMounted(async () => {
  console.log("回收站页面已加载");

  // 获取已删除待办列表数据
  await loadDeletedTodoList();

  // 监听新添加到回收站的待办
  uni.$on("todoDeleted", (todoData) => {
    // 重新加载数据以获取最新状态
    loadDeletedTodoList();
  });

  // 监听刷新回收站事件
  uni.$on("refreshTrashList", () => {
    loadDeletedTodoList();
  });
});

// 页面卸载时清理事件监听
onUnmounted(() => {
  uni.$off("todoDeleted");
  uni.$off("refreshTrashList");
});
</script>

<style scoped>
.content {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  background-color: #f5f5f5;
  width: 100%;
  overflow-x: hidden;
}

.page-body {
  flex: 1;
  display: flex;
  flex-direction: column;
  padding: 0;
  position: relative;
  width: 100%;
  overflow-x: hidden;
  box-sizing: border-box;
}

.todo-container {
  flex: 1;
  padding: 0 20rpx;
  padding-bottom: 100rpx;
  box-sizing: border-box;
  width: 100%;
}

.empty-list {
  padding: 100rpx 0;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.empty-icon {
  font-size: 80rpx;
  color: #cccccc;
  margin-bottom: 20rpx;
}

.empty-text {
  font-size: 28rpx;
  color: #999999;
}
</style>
